package com.kunya.common.common;

import com.kunya.common.util.PropertiesUtil;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**   
* @Description:redis分片连接池
* @author zp  
* @date 2018年4月29日  
*/  
public class RedisShardedPool {
	private static ShardedJedisPool pool;
	private static Integer maxTotal=Integer.parseInt(PropertiesUtil.getProperty("redis.max.total"));
	private static Integer maxIdle=Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle"));
	private static Integer minIdle=Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle"));
	private static boolean testOnBorrow=Boolean.parseBoolean(PropertiesUtil.getProperty("redis.max.total"));
	private static boolean testOnReturn=Boolean.parseBoolean(PropertiesUtil.getProperty("redis.max.total"));
	
	private static String redisIp1=PropertiesUtil.getProperty("redis1.ip");
	private static int redisPort1=Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));
	
	private static String redisIp2=PropertiesUtil.getProperty("redis2.ip");
	private static int redisPort2=Integer.parseInt(PropertiesUtil.getProperty("redis2.port"));
	
	
	private static void initPool() {
		//设置分片连接池配置参数
		JedisPoolConfig config=new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		config.setTestOnBorrow(testOnBorrow);
		JedisShardInfo shardInfo1=new JedisShardInfo(redisIp1, redisPort1,1000*2);
		JedisShardInfo shardInfo2=new JedisShardInfo(redisIp2, redisPort2,1000*2);
		List<JedisShardInfo> jedisShardInfoList=new ArrayList<JedisShardInfo>(2);
		jedisShardInfoList.add(shardInfo1);
		jedisShardInfoList.add(shardInfo2);
		
		//初始化分片连接池
		//默认Hashing.MURMUR_HASH，分片策略哈希一致性
		pool=new ShardedJedisPool(config,jedisShardInfoList,Hashing.MURMUR_HASH,Sharded.DEFAULT_KEY_TAG_PATTERN);
	}
	
	static {
		//静态初始化 分片redis
		initPool();
		
	}
	
	
	public static ShardedJedis getJedis() {
		//从连接池获取实例
		return pool.getResource();
	}
	
	
	public static void returnBrokenResource(ShardedJedis jedis) {
			//返还连接池坏实例
			pool.returnBrokenResource(jedis);
		
	}
	public static void returnResource(ShardedJedis jedis) {
			//返还连接池实例
			pool.returnResource(jedis);
		
	}
	
	public static void main(String[] args) {
		ShardedJedis jedis=pool.getResource();
		for(int i=0;i<10;i++) {
			jedis.set("key"+i, "value"+i);
		}
		returnResource(jedis);
//		pool.destroy();
		System.out.println("end");
	}
	
	
	
	
	

}
